#!/bin/bash

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
WHITE='\033[1;37m'
NC='\033[0m' # No Color

# 彩色输出函数
info() { echo -e "${WHITE}[信息]${NC} $1"; }
warn() { echo -e "${YELLOW}[警告]${NC} $1"; }
error() { echo -e "${RED}[错误]${NC} $1"; exit 1; }
title() { echo -e "${BLUE}$1${NC}"; }

# 欢迎信息
title "================================================"
title "  Rsync实时目录同步服务卸载工具"
title "================================================"
info " 功能说明:"
info " 1. 停止并禁用同步服务"
info " 2. 删除系统服务文件"
info " 3. 删除同步脚本"
info " 4. 保留日志文件和同步目录"
info ""
warn " 注意: 此操作不可逆，将永久删除同步服务!"
title "================================================"

# 检查root权限
[ "$(id -u)" != "0" ] && error "此脚本需要root权限执行!"

# 确认卸载
warn "您确定要卸载Rsync实时目录同步服务吗? (y/n)"
read -p "" -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    info "卸载已取消"
    exit 0
fi

# 停止并禁用服务
if systemctl is-active --quiet rsync-realtime-dir-sync; then
    info "正在停止服务..."
    systemctl stop rsync-realtime-dir-sync
fi

if systemctl is-enabled --quiet rsync-realtime-dir-sync; then
    info "正在禁用服务..."
    systemctl disable rsync-realtime-dir-sync
fi

# 删除服务文件
SERVICE_FILE="/etc/systemd/system/rsync-realtime-dir-sync.service"
if [ -f "$SERVICE_FILE" ]; then
    info "删除服务文件: $SERVICE_FILE"
    rm -f "$SERVICE_FILE"
    systemctl daemon-reload
    systemctl reset-failed
else
    warn "服务文件不存在: $SERVICE_FILE"
fi

# 删除同步脚本
SYNC_SCRIPT="/usr/local/bin/rsync-realtime-dir-sync.sh"
if [ -f "$SYNC_SCRIPT" ]; then
    info "删除同步脚本: $SYNC_SCRIPT"
    rm -f "$SYNC_SCRIPT"
else
    warn "同步脚本不存在: $SYNC_SCRIPT"
fi

# 完成信息
title "================================================"
info " Rsync实时目录同步服务已成功卸载!"
info ""
info " 以下内容未被删除:"
info " - 日志文件: /var/log/rsync-realtime-dir-sync.log"
info " - 源目录和目标目录"
info ""
warn " 如需完全清理，请手动删除上述内容"
title "================================================"